﻿using auto_chat_win;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;


namespace auto_win
{
    public partial class MainForm : System.Windows.Forms.Form
    {

        private WechatMgr wechatMgr;
        private List<WechatCrowd> crowds;//微信群
        private List<WechatApplication> apps; //微信程序（多开就多个程序）
        private List<CrowdTask> tasks;
        private bool running = false;
        private Dictionary<string, string> sayHelloDict = new Dictionary<string, string>(); //每个群的好友打招呼用语
        private Dictionary<string, DateTime> lastSendTimeDict = new Dictionary<string, DateTime>(); //记录上次发送的时间
        private Dictionary<string, int> lastSendCountDict = new Dictionary<string, int>(); //记录上次发送的时候的群人数
        private CrowdMember lastAdded; //记录上次加入群的人
        private string version = "版本号：251010";

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            wechatMgr = new WechatMgr(this);
            log(version);
        }



        //步骤1，获取服务器微信群
        private void getCrowd()
        {
            List<WechatCrowd> crowds = API.getCrowd();
            sayHelloDict.Clear();
            if (crowds == null)
            {
                log("没有在服务器找到事先设置好的群信息");
            }
            else
            {
                log($"从服务器上获取到{crowds.Count}个微信群：\r\n");
                foreach (var c in crowds)
                {
                    log($"{c.crowdName}\t|\t{c.wechatNickname}\r\n");
                    if(c.comment != null && c.comment != "")
                    {
                        sayHelloDict.Add(c.crowdName, c.comment);
                    }
                }
                this.crowds = crowds;
                ShowAccount();
            }
        }

        private void ShowAccount()
        {
            Dictionary<string, WechatApplication> dict = new Dictionary<string, WechatApplication>();
            var set = new HashSet<string>();
            foreach (var crowd in crowds)
            {
                set.Add(crowd.wechatNickname);
            }
            foreach (var nick in set)
            {
                var app = new WechatApplication();
                app.wechatAccount = nick;
                dict.Add(nick, app);
            }
            var wechatApps = wechatMgr.ScanWechatProcess(dict);
            this.apps = wechatApps;
            dataGridView1.Rows.Clear();
            foreach (var app in wechatApps)
            {
                string[] row = { app.wechatAccount, app.processId + "" };
                dataGridView1.Rows.Add(row);
            }
        }
        //步骤2，获取定时任务
        private void getTask()
        {
            List<CrowdTask> tasks = API.getTasks();
            if (tasks == null)
            {
                log("没有在服务器找到事先设置好的群发配置");
            }
            else
            {
                log($"从服务器上获取到{tasks.Count}个配置：\r\n");
                foreach (var c in tasks)
                {
                    if(c.type == 0)
                    {
                        log($"定时群发配置，每隔{c.interval}分钟群发一次");
                    }
                    else
                    {
                        log($"条件群发配置，每加入{c.interval}人群发一次");
                    }
                }
                this.tasks = tasks;
            }
        }

        //开启每分钟扫描
        private async void startMonitor()
        {
            running = true;
            log("启动定时任务", true);
            while (running) // 无限循环，模拟持续运行的程序
            {
                try
                {
                    eachCycle();
                }
                catch (Exception e)
                {
                    log("报错:" + e.Message + e.StackTrace, true);
                    Trace.TraceError(e.StackTrace);
                }
                await Task.Delay(30000); // 等待30秒
            }
        }

        private void eachCycle()
        {
            var now = DateTime.Now;
            foreach (var app in apps)
            {
                //1 加好友
                var friends = wechatMgr.ScanNewFriends(app);
                if (friends.Count > 0)
                {
                    if(friends.Count == 1)
                    {
                        //刚添加好友，不一定能搜索到
                        System.Threading.Thread.Sleep(2000);
                    }
                    foreach (var friend in friends)
                    {
                        log($"加入好友：[{friend.crowdname}]的[{friend.nickname}][{friend.wechatId}]");
                        if (sayHelloDict.ContainsKey(friend.crowdname))
                        {
                            System.Threading.Thread.Sleep(1000);
                            wechatMgr.SendMessage(app, sayHelloDict[friend.crowdname], friend.comment, false);
                        }
                    }
                    API.saveFriends(friends);
                }


                foreach (var crowd in crowds)
                {
                    if (crowd.wechatNickname.Equals(app.wechatAccount))
                    {
                        //2 查看加入群的用户
                        int count;
                        List<string> messages = wechatMgr.ScanNewMessage(app, crowd.crowdName, out count);
                        var joins = new List<CrowdMember>();
                        var key1 = "\"加入了群聊";
                        var key2 = "\"邀请\"";
                        foreach (var message in messages)
                        {
                            //"龙"邀请"星参谋- "加入了群聊
                            if (message.EndsWith(key1))
                            {
                                var pos = message.IndexOf(key2);
                                if (pos > 0)
                                {
                                    var inviteBy = message.Substring(1, pos - 1);
                                    var nickname = message.Substring(pos + key2.Length, message.Length - key1.Length - pos - key2.Length);
                                    var nicknames = nickname.Split('、');
                                    foreach (var name in nicknames)
                                    {
                                        var j = new CrowdMember();
                                        j.crowdId = crowd.id;
                                        j.crowdname = crowd.crowdName;
                                        j.inviteBy = inviteBy;
                                        j.nickname = name;
                                        joins.Add(j);
                                    }
                                }
                            }
                        }
                        sendFriends(joins);


                        //3 群发消息                        
                        string current = now.ToString("HH:mm");
                        foreach (var task in tasks)
                        {
                            if (task.startTime.CompareTo(current) <= 0 && task.endTime.CompareTo(current) >= 0)
                            {
                                var key = task.id + "-" + crowd.id;
                                if (task.type == 0)
                                {
                                    if (!lastSendTimeDict.ContainsKey(key))
                                    {
                                        lastSendTimeDict.Add(key, now);
                                    }
                                    else
                                    {
                                        var lastSendAt = lastSendTimeDict[key];
                                        if (lastSendAt <= now.AddMinutes(-task.interval))
                                        {
                                            sendMessage(app, task, crowd);
                                            lastSendTimeDict[key] = now;
                                        }
                                    }
                                }
                                else
                                {
                                    if (!lastSendCountDict.ContainsKey(key))
                                    {
                                        lastSendCountDict.Add(key, count);
                                    }
                                    else
                                    {
                                        var lastCount = lastSendCountDict[key];
                                        Trace.WriteLine($"lastCount={lastCount}, count={count}, interval={task.interval}");
                                        if (count >= lastCount + task.interval)
                                        {
                                            lastSendCountDict[key] = count;
                                            sendMessage(app, task, crowd);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void sendMessage(WechatApplication app, CrowdTask task, WechatCrowd crowd)
        {
            bool success = wechatMgr.SendMessage(app, task.message, crowd.crowdName, true);
            if (success)
            {
                API.sendMessage(new Message(crowd.crowdName, 0, crowd.wechatNickname, task.message));
            }
        }

        private void sendFriends(List<CrowdMember> joins)
        {
            if(joins.Count == 0)
            {
                return;
            }
            Trace.WriteLine($"共发现{joins.Count}条加群记录");
            if (lastAdded != null)
            { //除去重复发送的
                int pos = joins.IndexOf(lastAdded);
                if (pos == joins.Count - 1)
                {
                    return;
                }
                if (pos > -1)
                {
                    Trace.WriteLine($"从第{pos + 2}个开始发送");
                    int startPos = pos + 1;
                    joins = joins.GetRange(startPos, joins.Count - startPos);
                }
            }
            Trace.WriteLine($"实际发送{joins.Count}条加群记录");
            API.saveJoins(joins);
            lastAdded = joins[joins.Count - 1];
        }

        public void log(string msg, bool wrap = false)
        {
            if (wrap)
            {
                textBox1.Text += "\r\n" + msg + "\r\n";
            }
            else
            {
                textBox1.Text += msg + "\r\n";
            }
            // 滚动到文本末尾
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.ScrollToCaret();
        }

        private void start_btn_Click(object sender, EventArgs e)
        {
            start_btn.Enabled = false;
            //步骤1，获取服务器微信群
            getCrowd();
            //步骤2，获取定时任务
            getTask();
            //开启每分钟扫描
            System.Threading.Thread.Sleep(1000);
            startMonitor();
            stop_btn.Enabled = true;
        }

        private void stop_btn_Click(object sender, EventArgs e)
        {
            stop_btn.Enabled = false;
            running = false;
            log("关闭定时任务", true);
            System.Threading.Thread.Sleep(1000);
            start_btn.Enabled = true;

        }

        private void account_btn_Click(object sender, EventArgs e)
        {
            List<Product> prods = API.getProducts();
            User user = API.getInfo();
            var accountForm = new AccountForm(prods, user);
            accountForm.ShowDialog();
        }
    }
}
